﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Reborn_WorldServer.App1AppHandler.Spells.Interfaces;
using App1AppHandler;
using Reborn_WorldServer;

namespace Reborn_Server.App1AppHandler
{
    public class Spell_DeathSpirit : Buff, IDeathEffect
    {
        //We MUST store the casting creature base in order to apply SD flags when the death effect runs
        //Due to this, these buffs cannot save and must be removed if the casting creature is removed from the server
        private CreatureBase castingCreatureBase = null;

        public Spell_DeathSpirit()
        {
            minutesLeft = 10;
            saveBuff = false;
        }

        public void runDeathEffect()
        {
            Spell_FirePillars instantTargetAOE = new Spell_FirePillars();

            SpellIcon iconToSend = this.spellIcon.clone();

            //Turn offensive off for resilience. It will heal the casters faction
            if (iconToSend.Skill == "Resilience")
                iconToSend.Offensive = false;

            instantTargetAOE.InstantCast(this.castingCreatureBase, TargetCreatureBase, iconToSend, CastingCreatureLevel);

            //No need to remove the spell, the death will do it
        }

        public void Cast(CreatureBase myCreatureBase, int CastLevel, long CreatureGUID)
        {
            List<MapItem> MapItemsWithin12;
            if (base.InitializeCast(myCreatureBase, CastLevel, CreatureGUID, true, out MapItemsWithin12) == false)
                return;

            castingCreatureBase = myCreatureBase;

            foreach (MapItem mapitem in MapItemsWithin12)
            {
                if (Math.Abs(mapitem.MapX - TargetCreatureBase.MapX) <= 8 && Math.Abs(mapitem.MapY - TargetCreatureBase.MapY) <= 8)
                {
                    foreach (CreatureBase creaturebase in mapitem.CreaturesBases)
                    {
                        if (creaturebase is Character)
                        {
                            Character character = (Character)creaturebase;
                            character.PlaySound("BuffCast", TargetCreatureBase.MapX, TargetCreatureBase.MapY);
                        }
                    }
                }
            }

            TargetCreatureBase.buffManager.UpdateBuffs();
            
            //Save this buff to the casting creatures Tied Buffs. If the casting creature gets removed from the server
            //this buff will get removed from the target creature.
            myCreatureBase.buffManager.addTiedBuff(this);

            spellTimer.Start();
        }

        public override void RemoveSpell(bool updateBuffs, bool sendMessage)
        {
            base.RemoveSpell(updateBuffs, sendMessage);

            //Remove this buff from the casting creatures tied buffs.
            castingCreatureBase.buffManager.removeTiedBuff(this);
        }
    }
}
